package com.baidu.foodrecipe.ui.fragment.recipes.details

import android.os.Bundle
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.transition.AutoTransition
import com.baidu.foodrecipe.R
import com.baidu.foodrecipe.base.BaseFragment
import com.baidu.foodrecipe.databinding.FragmentDetailsBinding
import com.baidu.foodrecipe.ui.adapters.DetailAdapter
import com.baidu.foodrecipe.ui.fragment.favorite.FavoriteViewModel
import com.google.android.material.tabs.TabLayoutMediator

class DetailsFragment : BaseFragment<FragmentDetailsBinding>() {
    private val detailViewModel: DetailViewModel by activityViewModels()
    private val favoriteViewModel: FavoriteViewModel by activityViewModels()
    private val args: DetailsFragmentArgs by navArgs()
    private var isFavorited = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //设置共享动画进入的转换动画效果  尺寸变化
        sharedElementEnterTransition = AutoTransition()
        sharedElementReturnTransition = AutoTransition()

        detailViewModel.result = args.recipe
    }

    override fun initUI(savedInstanceState: Bundle?) {
        mBinding.ivBack.setOnClickListener {
            findNavController().popBackStack()
        }

        //配置ViewPager每页显示内容的adapter
        mBinding.detailViewPager.adapter = DetailAdapter(requireActivity())

        //viewpager和tabLayout绑定
        TabLayoutMediator(mBinding.detailTabLayout, mBinding.detailViewPager) { tab, position ->
            when (position) {
                0 -> tab.text = "Overview"
                1 -> tab.text = "Ingredients"
                2 -> tab.text = "Instructions"
            }
        }.attach()

        //处理收藏按钮逻辑
        checkFavorite()

        //给收藏按钮添加点击事件
        mBinding.ivFavorite.setOnClickListener {
            if (isFavorited){
                favoriteViewModel.removeFavoriteRecipe(detailViewModel.result!!){
                    if (!it){
                        mBinding.ivFavorite.setColorFilter(requireContext().getColor(R.color.white))
                        isFavorited = false
                    }
                }
            }else{
                favoriteViewModel.addFavoriteRecipe(detailViewModel.result!!){
                    if (!it){
                        mBinding.ivFavorite.setColorFilter(requireContext().getColor(R.color.yellow))
                        isFavorited = true
                    }
                }
            }
        }
    }

    private fun checkFavorite(){
        isFavorited = favoriteViewModel.isFavorited(detailViewModel.result!!)
        if (isFavorited){
            mBinding.ivFavorite.setColorFilter(requireContext().getColor(R.color.yellow))
        }else{
            mBinding.ivFavorite.setColorFilter(requireContext().getColor(R.color.white))
        }
    }
}